﻿
var shaders;	//着色器
var shadersMap = {};		//着色vo


$(function(){
	$('.edit-wrapper').append('<button class="el-button" style="color: red" id="download_png">点此下载全部logo</button>')
	$('#download_png').click(function(){
		if (confirm("是否下载全部logo？网页中有"+getLogoCount()+"个logo。")) {
			shaderInit();
			converDownload();
		}
	});
});


function getLogoCount() {

	var cards = $('.card');
	var tips = $('.card.tips')
	var loadMore = $('.card.load-more')
	return cards.length - tips.length - loadMore.length;
}

function converDownload() {
	
	var cards = $('.card');
	for(var i=0;i<cards.length;i++) {
		var svg = $(cards[i]).find('svg');
		console.log()
		if(svg.length != 0 && $(svg.context).attr('class')=='card') {
			drawImage(svgTag(svg[0].innerHTML), i+'.png')
		}
	}
}

function drawImage(data, name) {
	
	var dd = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(data)));
	var img = new Image();
	img.src = dd;
	
	/**
	 * 	图片预览
	 */
//	document.getElementById("help-div").appendChild(img);
	
	img.onload = function () {
		
		var canvas = document.createElement('canvas');
		canvas.width = img.width;
		canvas.height = img.height;
		var ctx = canvas.getContext('2d');
		ctx.drawImage(img, 0, 0);
		
		var a = document.createElement('a');
		a.download = name;
		a.href = canvas.toDataURL("image/png");
		a.click();
	}
	
}



function svgTag(data) {
	
	var svg_header = '<svg data-v-73fdaaa2="" version="1.0" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" viewBox="0 0 340.000000 250.000000" preserveAspectRatio="xMidYMid meet" color-interpolation-filters="sRGB" class="el-tooltip" style="margin: auto;">'
	var svg_footer = '</svg>';
	
	var fill = matchShaderId(data)
	if (fill) {
		var shaderId = matchUrlId(fill);
		if (shaderId) {
			return svg_header + shadersMap[shaderId] + data + svg_footer;
		}
	}
	
	return svg_header + data + svg_footer;
}


/**
 * 	单例初始化文中所有的着色器标签
 */
function shaderInit() {
	
	var $html = $('html').html();
	var reg = /<linearGradient id="(.*?)".*<\/linearGradient>/ig;
	
	shaders = $html.match(reg);
	
	var reg2 = /<linearGradient id="(.*?)".*<\/linearGradient>/;
	$.each(shaders, function() {
		var tmp = reg2.exec(this);
		shadersMap[tmp[1]] = tmp[0];
	});
	return shaders;
}



/**
 * 	匹配着色器Id
 * @param {Object} content	svg标签里面的内容
 */
function matchShaderId(content) {
	
	var reg = /<rect.*fill="(.*?)"/;
	if (reg.test(content)) {	
		return reg.exec(content)[1];
	}else {
		return false;
	}
}


/**
 * 	匹配URL地址
 * @param {Object} content
 */
function matchUrlId(content) {
	 	
	 var reg = /url\(#(.*?)\)/;
	 if (reg.test(content)) {
	 	return reg.exec(content)[1];
	 }else {
	 	return false;
	 }
	 
}
